package com.feihong.yw189.bluetooth.startwritecard;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.bluetooth.listener.ReadIccidListener;
import com.feihong.yw189.bluetooth.listener.WriteCardListener;
import com.feihong.yw189.bluetooth.utils.util.TextUtil;
import com.kaeridcard.client.BtReaderClient;
import com.kaeridcard.client.IClientCallBack;
import com.kaeridcard.client.IdCardItem;

import static com.feihong.yw189.app.App.showToast;


/**
 * KtT8000写卡
 */

public class Kt8000Write {
    private String blueAddress;
    private static Activity mActivity;
    private ReadIccidListener mReadIccidListener;
    private WriteCardListener mWriteCardListener;
    private BtReaderClient mClient;
    private boolean is_bt_connect = false;
    private int mType;
    public Kt8000Write(Activity context, String blueAddress,int mType, ReadIccidListener readIccidListener
            , WriteCardListener writeCardListener) {
        this.mActivity = context;
        this.blueAddress = blueAddress;
        this.mType = mType;
        this.mReadIccidListener = readIccidListener;
        this.mWriteCardListener = writeCardListener;
    }

    /**
     * kt8000的回调
     */
    private IClientCallBack mCallback = new IClientCallBack() {
        @Override
        public void onBtState(final boolean is_connect) {
            mActivity.runOnUiThread(new Runnable() {
                public void run() {
                    if (is_connect) {
//                        showToast("蓝牙已连接到");
                        Log.e("项目异常", "------蓝牙已连接------");
                    } else {
//                        showToast("蓝牙连接已断开");
                        Log.e("项目异常", "------蓝牙连接已断开------");
                    }
                    is_bt_connect = is_connect;
                }
            });
        }

        @Override
        public void onIddataHandle(IdCardItem idCardItem) {
        }
    };

    //******************************************读iccid************************************************
    public void connect() {
        mClient = new BtReaderClient(mActivity);
        if (mClient != null) {
            mClient.setCallBack(mCallback);
        }
        KaEr_ConnectCard();
    }

    /**
     * 卡尔  蓝牙写卡器KT8000
     */
    private void KaEr_ConnectCard() {
        if (!TextUtils.isEmpty(blueAddress)) {
            Log.e("项目异常", "------blueAddress------" + blueAddress);
            boolean connresult = mClient.connectBt(blueAddress);
            if (connresult) {
//                ToastUtils.showShortToast(mActivity, "蓝牙连接成功");
                KEReadIccid();
            } else {
//                ToastUtils.showShortToast(mActivity, "蓝牙连接失败");
                mReadIccidListener.readIccidErr("蓝牙连接失败");
            }
        }
    }


    /**
     * kt8000  读取ICCID
     */
    private void KEReadIccid() {
        byte[] szCheckRes = new byte[1];
        byte[] szImsi2G = new byte[18];
        byte[] szImsiLen2G = new byte[1];
        byte[] szImsi3G = new byte[18];
        byte[] szImsiLen3G = new byte[1];
        String result = "";
        try {
            boolean btState = mClient.getBtState();
            Log.e("项目异常", "------蓝牙连接------" + btState);
            if (btState) {
                result = mClient.ReadICCID();
                if (result == null || result.equals("")) {
                    mReadIccidListener.readIccidErr("读取iccid失败2");
                } else {
                    byte[] resultByte = hexStringToByte(result);
                    int resultLen = (int) resultByte[6];
                    if (resultLen == 1) {
                        int error = (int) resultByte[7];
                        String strErr = "";
                        switch (error) {
                            case 1:
                                strErr = "sim卡未插入";
                                break;
                            case 2:
                                strErr = "sim卡插入但是不识别";
                                break;
                            case 4:
                                strErr = "sim卡插入但还未成功读取";
                                break;
                        }
                        mReadIccidListener.readIccidErr(strErr);
                    } else {
                        byte[] iccid = new byte[resultLen];
                        for (int i = 0; i < resultLen; i++) {
                            iccid[i] = resultByte[7 + i];
                        }
                        int readImsiRes = mClient.ReadIMSI((byte) 0x01, szCheckRes, szImsi2G, szImsiLen2G, szImsi3G, szImsiLen3G);
                        if (readImsiRes != 1) {
                            mReadIccidListener.readIccidErr("获取IMSI失败");
                            return;
                        } else {
                            Log.e("项目异常", "------读iccid成功------");
                            String imsi = TextUtil.bytesToASCString(szImsi3G);

                            if (mType == 0) {
                                if (imsi.contains("FFF")) {
                                    mReadIccidListener.readIccidIsChengKa(1617, new String(iccid).trim(), "此卡是白卡,无需重置");
                                } else {
                                    // 读iccid成功
                                    mReadIccidListener.readIccidSuc(0, new String(bytesToASCString(iccid)).trim(), imsi);
                                }
                            } else {
                                if (!imsi.contains("FFF")) {
                                    mReadIccidListener.readIccidIsChengKa(1617, new String(bytesToASCString(iccid)).trim(), "此卡是成卡,请换卡重试");
                                } else {
                                    // 读iccid成功
                                    mReadIccidListener.readIccidSuc(0, new String(bytesToASCString(iccid)).trim(), imsi);
                                }
                            }
                        }
                    }
                }
            } else {
                mReadIccidListener.readIccidErr("蓝牙未连接");
            }

        } catch (Exception e) {
            e.printStackTrace();
            mReadIccidListener.readIccidErr("读取iccid失败");
        }

    }
    //*******************************************写卡***********************************************

    /**
     * 卡尔KT8000       写卡方法   写IMSI
     */
    public void writeKEardTask(final byte[] szImsi, String Send_number) {
        if (!mClient.getBtState()) {        //蓝牙没有连接
            showToast("蓝牙未连接");
            mWriteCardListener.writeErr();
            return;
        }
        int writeImsiRes = mClient.WriteIMSI(szImsi, szImsi);
        if (writeImsiRes != 1) {
            mWriteCardListener.writeErr();
        } else {
            byte index = 1;// 短信中心号索引（每个sim卡可以有几个短信中心线性文件，从1开始）
//            int writeszMessAge = mClient.WriteSMSC(Send_number, index);
//            if (writeszMessAge != -2) {
//                mWriteCardListener.writeSuc();
//            } else {
//                mWriteCardListener.writeErr();
//            }
            int writeszMessAge = mClient.WriteSMSC(Send_number, index);

            if (writeszMessAge != 1) {
                mWriteCardListener.writeErr();
            } else {
                mWriteCardListener.writeSuc();
            }
        }
    }

    //******************************************************************************************
    public void closeClient() {
        if (mClient != null) {
            mClient.disconnectBt();
            Log.e("项目异常", "------disconnectBt------");
        }
    }

    /**
     * KT8000所需方法
     */
    public static byte[] hexStringToByte(String hex_str) {
        byte[] data_byte = new byte[hex_str.length() / 2];
        int byte_len = 0;
        for (int i = 0; i < hex_str.length(); i += 2) {
            data_byte[byte_len++] = HexToByte(hex_str.charAt(i), hex_str.charAt(i + 1));
        }
        return data_byte;
    }

    /**
     * KT8000所需方法
     */
    public static String bytesToASCString(byte[] src) {
        int len = src.length;
        if (src == null || len <= 0) {
            return null;
        }
        char[] result = new char[len];
        for (int i = 0; i < len; i++) {
            result[i] = (char) src[i];
        }
        return String.valueOf(result);
    }

    /**
     * kt8000   KT8000  KT8000   KT8000所需方法
     */
    public static byte HexToByte(char hex1, char hex2) {

        byte result = 0;
        for (int i = 0; i < 2; i++) {
            char c;
            if (i == 0)
                c = hex1;
            else
                c = hex2;
            byte b = 0;
            switch (c) {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    b = (byte) (c - '0');
                    break;
                case 'A':
                case 'B':
                case 'C':
                case 'D':
                case 'E':
                case 'F':
                    b = (byte) (10 + c - 'A');
                    break;
                case 'a':
                case 'b':
                case 'c':
                case 'd':
                case 'e':
                case 'f':
                    b = (byte) (10 + c - 'a');
                    break;
            }
            if (i == 0) {
                b = (byte) (b * 16);
            }
            result += b;
        }
        return result;
    }
}
